package mapkit.handlers
{
	import flash.events.MouseEvent;

	import mapkit.MapHandler;
	import mapkit.carto.MapPoint;

	public class Draw extends MapHandler
	{
		override public function get keyboardLocked():Boolean
		{
			return false;
		}

		override public function get mouseLocked():Boolean
		{
			return true;
		}

		override protected function load():void
		{
			super.load();
			map.doubleClickEnabled=true;
			map.addEventListener(MouseEvent.CLICK, clickHandler);
			map.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);

			addEventListener(DrawEvent.MULTI_CLICK_START, multiClickStartHandler);
			addEventListener(DrawEvent.MULTI_CLICK_UPDATE, multiClickUpdateHandler);
			addEventListener(DrawEvent.MULTI_CLICK_END, multiClickEndHandler);
		}

		override protected function unload():void
		{
			map.removeEventListener(MouseEvent.CLICK, clickHandler);
			map.removeEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);

			removeEventListener(DrawEvent.MULTI_CLICK_START, multiClickStartHandler);
			removeEventListener(DrawEvent.MULTI_CLICK_UPDATE, multiClickUpdateHandler);
			removeEventListener(DrawEvent.MULTI_CLICK_END, multiClickEndHandler);
			super.unload();
		}

		private var _multiClickPhase:int=MapHandlerEvent.IDLE;

		protected function clickHandler(event:MouseEvent):void
		{
			switch (_multiClickPhase)
			{
				case MapHandlerEvent.IDLE:
					_multiClickPhase=MapHandlerEvent.START;
					dispatchEvent(new DrawEvent(DrawEvent.MULTI_CLICK_START, this,
						map, event));
					_multiClickPhase=MapHandlerEvent.UPDATE;
					break;
				case MapHandlerEvent.UPDATE:
					dispatchEvent(new DrawEvent(DrawEvent.MULTI_CLICK_UPDATE, this,
						map, event));
					break;
			}
		}

		protected function doubleClickHandler(event:MouseEvent):void
		{
			var where:MapPoint=null;
			switch (_multiClickPhase)
			{
				case MapHandlerEvent.START:
					_multiClickPhase=MapHandlerEvent.IDLE;
				case MapHandlerEvent.UPDATE:
					_multiClickPhase=MapHandlerEvent.END;
					dispatchEvent(new DrawEvent(DrawEvent.MULTI_CLICK_END, this,
						map, event));
					_multiClickPhase=MapHandlerEvent.IDLE;
					break;
			}
		}

		protected function multiClickStartHandler(event:DrawEvent):void
		{
			map.acetate.graphics.clear();
			map.acetate.graphics.beginFill(0xff0000, 0.6);
			map.acetate.graphics.moveTo(event.relatedEvent.localX, event.relatedEvent.localY);
		}

		protected function multiClickUpdateHandler(event:DrawEvent):void
		{
			map.acetate.graphics.lineTo(event.relatedEvent.localX, event.relatedEvent.localY);
		}

		protected function multiClickEndHandler(event:DrawEvent):void
		{
			map.acetate.graphics.lineTo(event.relatedEvent.localX, event.relatedEvent.localY);
			map.acetate.graphics.endFill();
		}

	}
}